using System;
using System.Data;
using System.Configuration;
using Pheonix.Fashionzoomer.DAL;
using System.Data.SqlClient;
using System.Collections;
using Pheonix.CodeLibrary.Data;
using Pheonix.CodeLibrary;

/// <summary>
/// Summary description for Category
/// </summary>

namespace Pheonix.Fashionzoomer.Entity.SqlServer2000
{
    [System.ComponentModel.DataObject]
    public class Category : SqlServerDAO
    {
        #region Category Private Fields

		private Int32 _id;
		private String _categoryName;
		private Int32 _parentCategoryId;
		private Int32 _itemCount;
		private DateTime _createdOn;
		private DateTime _lastUpdate;
		private Int32 _totalView;
		private String _categoryImage;

        #endregion

        #region Category Constractors

		public Category(){}

		public Category
		(
			Int32 id,
			String categoryName,
			Int32 parentCategoryId,
			Int32 itemCount,
			DateTime createdOn,
			DateTime lastUpdate,
			Int32 totalView,
			String categoryImage

		)
		{
			this._id = id;
			this._categoryName = categoryName;
			this._parentCategoryId = parentCategoryId;
			this._itemCount = itemCount;
			this._createdOn = createdOn;
			this._lastUpdate = lastUpdate;
			this._totalView = totalView;
			this._categoryImage = categoryImage;
		}

        #endregion

        #region Category Properties

		public Int32 Id
		{
			get{ return this._id; }
			set{ this._id = value; }
		}

		public String CategoryName
		{
			get{ return this._categoryName; }
			set{ this._categoryName = value; }
		}

		public Int32 ParentCategoryId
		{
			get{ return this._parentCategoryId; }
			set{ this._parentCategoryId = value; }
		}

		public Int32 ItemCount
		{
			get{ return this._itemCount; }
			set{ this._itemCount = value; }
		}

		public DateTime CreatedOn
		{
			get{ return this._createdOn; }
			set{ this._createdOn = value; }
		}

		public DateTime LastUpdate
		{
			get{ return this._lastUpdate; }
			set{ this._lastUpdate = value; }
		}

		public Int32 TotalView
		{
			get{ return this._totalView; }
			set{ this._totalView = value; }
		}

		public String CategoryImage
		{
			get{ return this._categoryImage; }
			set{ this._categoryImage = value; }
		}


        #endregion

        #region Category Static Methods

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Insert, true)]
        public static Int32 CreateNewCategory
        (
			String categoryName,
			Int32 parentCategoryId,
			Int32 itemCount,
			DateTime createdOn,
			DateTime lastUpdate,
			Int32 totalView,
			String categoryImage

        )
        {
            //creating an empty Category object
            Category category = new Category();
            category.CategoryName = categoryName;
			category.ParentCategoryId = parentCategoryId;
			category.ItemCount = itemCount;
			category.CreatedOn = createdOn;
			category.LastUpdate = lastUpdate;
			category.TotalView = totalView;
			category.CategoryImage = categoryImage;

            return Category.CreateNewCategory(category);
        }

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, true)]
        public static bool UpdateCategory
        (
			Int32 id,
			String categoryName,
			Int32 parentCategoryId,
			Int32 itemCount,
			DateTime createdOn,
			DateTime lastUpdate,
			Int32 totalView,
			String categoryImage

        )
        {
            Category category = Category.GetCategoryById(id);
            category.CategoryName = categoryName;
			category.ParentCategoryId = parentCategoryId;
			category.ItemCount = itemCount;
			category.CreatedOn = createdOn;
			category.LastUpdate = lastUpdate;
			category.TotalView = totalView;
			category.CategoryImage = categoryImage;

            return Category.UpdateCategory(category);
        }

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, true)]
        public static bool DeleteCategory
        (
            Int32 id
        )
        {
            //Validate Input
            if (id <= GetIdMinValue)
                throw (new ArgumentOutOfRangeException("id in Category"));

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            AddParameterToSqlCmd(sqlCmd, "@Id", SqlDbType.Int, 0, ParameterDirection.Input, id);
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_CATEGORY_DELETECATEGORY);
            GetOneData(sqlCmd);
            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return (returnValue == 0 ? false : true);

        }

        public static bool DeleteCategoryList(System.Collections.Generic.List<Int32> idListToDelete)
        {
            //Validate Input
            foreach (Int32 id in idListToDelete)
                if (id <= GetIdMinValue)
                    throw (new ArgumentOutOfRangeException("id in Category"));

            //performing deletion operation //

            string csvString = Utility.MakeCSV(idListToDelete);

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            AddParameterToSqlCmd(sqlCmd, "@IdList", SqlDbType.NVarChar, csvString.Length, 
                ParameterDirection.Input, csvString);
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_CATEGORY_DELETECATEGORYLIST);
            GetOneData(sqlCmd);
            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return (returnValue == idListToDelete.Count ? true : false);
        }
		
		[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, false)]
		public static CustomCollection<Category> GetCategoryByParentCategoryId(Int32 parentCategoryId)
		{
			if(parentCategoryId <= GetIdMinValue)
				throw (new ArgumentOutOfRangeException("parentCategoryId in Category"));

			SqlCommand sqlCmd = new SqlCommand();
			AddParameterToSqlCmd(sqlCmd, "@ParentCategoryId", SqlDbType.Int, 0, ParameterDirection.Input, parentCategoryId);
			SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_CATEGORY_GETCATEGORYBYPARENTCATEGORYID);
			GenerateCollectionFromReader dg = new GenerateCollectionFromReader(GenerateCategoryCollectionFromReader);
			CustomCollection<Category> objCollection = ((CustomCollection<Category>)GetAllData(sqlCmd, dg));

			if (objCollection.Count > 0)
				return objCollection;
			else
				return null;
		}

        #endregion

        #region Category Instance Methods
        
        public bool Save()
		{
			if(Id <= GetIdMinValue)
			{
				Int32 TempId=CreateNewCategory(this);
				if(TempId>0)
				{
					_id=TempId;
					return true;
				}
				else
				{
					// error occurs
					return false;
				}
			}
			else
			{	//This is a update Command
				return (UpdateCategory(this));
			}
		}

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static CustomCollection<Category> GetAllCategory()
        {
            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_CATEGORY_GETALLCATEGORY);
            GenerateCollectionFromReader result = new GenerateCollectionFromReader(GenerateCategoryCollectionFromReader);
            CustomCollection<Category> objCollection = ((CustomCollection<Category>)GetAllData(sqlCmd, result));

            return objCollection;
        }

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static CustomCollection<Category> GetAllCategoryPaged(String orderBy, Int32 startRowIndex, Int32 maximumRows)
        {
            //Validate Input
            if (orderBy == "")
                orderBy = "Id";

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@orderby", SqlDbType.VarChar, 50, ParameterDirection.Input, orderBy);
            AddParameterToSqlCmd(sqlCmd, "@startRowIndex", SqlDbType.Int, 0, ParameterDirection.Input, startRowIndex);
            AddParameterToSqlCmd(sqlCmd, "@maximumRows", SqlDbType.Int, 0, ParameterDirection.Input, maximumRows);

            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_CATEGORY_GETALLCATEGORYPAGED);

            GenerateCollectionFromReader result = new GenerateCollectionFromReader(GenerateCategoryCollectionFromReader);
            CustomCollection<Category> objCollection = ((CustomCollection<Category>)GetAllData(sqlCmd, result));
            return objCollection;
        }

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static int GetAllCategoryPagedCount(String orderBy, Int32 startRowIndex, Int32 maximumRows)
        {
            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();

            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_CATEGORY_GETALLCATEGORYPAGEDCOUNT);
            GetOneData(sqlCmd);

            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return returnValue;
        }

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static Category GetCategoryById(Int32 id)
        {
            if (id <= GetIdMinValue)
                throw (new ArgumentOutOfRangeException("id in Category"));

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@Id", SqlDbType.Int, 0, ParameterDirection.Input, id);
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_CATEGORY_GETCATEGORYBYID);
            GenerateCollectionFromReader result = new GenerateCollectionFromReader(GenerateCategoryCollectionFromReader);
            CustomCollection<Category> objCollection = ((CustomCollection<Category>)GetAllData(sqlCmd, result));

            if (objCollection.Count > 0)
                return (Category)objCollection[0];
            else
                return null;
        }

        public static Int32 CreateNewCategory(Category newCategory)
        {
            // validate Parameters
            if (newCategory == null)
                throw (new ArgumentNullException("newCategory in Category"));

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);

            AddParameterToSqlCmd(sqlCmd, "@CategoryName", SqlDbType.NVarChar, 64, ParameterDirection.Input, newCategory.CategoryName);
			AddParameterToSqlCmd(sqlCmd, "@ParentCategoryId", SqlDbType.Int, 0, ParameterDirection.Input, newCategory.ParentCategoryId);
			AddParameterToSqlCmd(sqlCmd, "@ItemCount", SqlDbType.Int, 0, ParameterDirection.Input, newCategory.ItemCount);
			AddParameterToSqlCmd(sqlCmd, "@CreatedOn", SqlDbType.DateTime, 0, ParameterDirection.Input, newCategory.CreatedOn);
			AddParameterToSqlCmd(sqlCmd, "@LastUpdate", SqlDbType.DateTime, 0, ParameterDirection.Input, newCategory.LastUpdate);
			AddParameterToSqlCmd(sqlCmd, "@TotalView", SqlDbType.Int, 0, ParameterDirection.Input, newCategory.TotalView);
			AddParameterToSqlCmd(sqlCmd, "@CategoryImage", SqlDbType.NVarChar, 150, ParameterDirection.Input, newCategory.CategoryImage);

            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_CATEGORY_CREATENEWCATEGORY);
            GetOneData(sqlCmd);
            return ((Int32)sqlCmd.Parameters["@ReturnValue"].Value);

        }

        public static bool UpdateCategory(Category newCategory)
        {
            // validate Parameters
            if (newCategory == null)
                throw (new ArgumentNullException("newCategory"));

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);

            AddParameterToSqlCmd(sqlCmd, "@Id", SqlDbType.Int, 0, ParameterDirection.Input, newCategory.Id);
            AddParameterToSqlCmd(sqlCmd, "@CategoryName", SqlDbType.NVarChar, 64, ParameterDirection.Input, newCategory.CategoryName);
			AddParameterToSqlCmd(sqlCmd, "@ParentCategoryId", SqlDbType.Int, 0, ParameterDirection.Input, newCategory.ParentCategoryId);
			AddParameterToSqlCmd(sqlCmd, "@ItemCount", SqlDbType.Int, 0, ParameterDirection.Input, newCategory.ItemCount);
			AddParameterToSqlCmd(sqlCmd, "@CreatedOn", SqlDbType.DateTime, 0, ParameterDirection.Input, newCategory.CreatedOn);
			AddParameterToSqlCmd(sqlCmd, "@LastUpdate", SqlDbType.DateTime, 0, ParameterDirection.Input, newCategory.LastUpdate);
			AddParameterToSqlCmd(sqlCmd, "@TotalView", SqlDbType.Int, 0, ParameterDirection.Input, newCategory.TotalView);
			AddParameterToSqlCmd(sqlCmd, "@CategoryImage", SqlDbType.NVarChar, 150, ParameterDirection.Input, newCategory.CategoryImage);

            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_CATEGORY_UPDATECATEGORY);
            GetOneData(sqlCmd);
            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return (returnValue == 0 ? false : true);
        }

        #endregion

        #region Category Related Collections
        /// <summary>
        /// Creates and returns a strongly typed collection of Category custom entity. 
        /// The colelction is created through iterating on the IdataReader object which contains 
        /// Category information, as a set of records, similar to tabular format.
        /// </summary>
        public static IList GenerateCategoryCollectionFromReader(IDataReader returnData)
        {

            //creating the instance of Category collection
            CustomCollection<Category> colCategory = new CustomCollection<Category>();

            //Iterating thriugh the data reader, to generate Category collection.

            //getting the Category collection by iterating thru the data reader
            while (returnData.Read())
            {
                //passing the Category constructor parameters from the current instance of data reader fields.
                Category newCategory = new Category
                (
                    returnData["id"] == System.DBNull.Value ? GetIdMinValue : (Int32)returnData["id"],
                    returnData["category_name"] == System.DBNull.Value ? String.Empty : (String)returnData["category_name"],
					returnData["parent_category_id"] == System.DBNull.Value ? Int32.MinValue : (Int32)returnData["parent_category_id"],
					returnData["item_count"] == System.DBNull.Value ? Int32.MinValue : (Int32)returnData["item_count"],
					returnData["created_on"] == System.DBNull.Value ? DateTime.MinValue : (DateTime)returnData["created_on"],
					returnData["last_update"] == System.DBNull.Value ? DateTime.MinValue : (DateTime)returnData["last_update"],
					returnData["total_view"] == System.DBNull.Value ? Int32.MinValue : (Int32)returnData["total_view"],
					returnData["category_image"] == System.DBNull.Value ? String.Empty : (String)returnData["category_image"]

                );
                //adding the Category to the collection
                colCategory.Add(newCategory);
            }

            //returns the collection of Category 
            return (colCategory);
        }

        #endregion

        #region Constants and Default Values

        public static Int32 GetIdMinValue
        {
            get
            {
                return 0;
            }
        }

        //contants
        internal const string SPR_CATEGORY_CREATENEWCATEGORY = "spr_Category_CreateNewCategory";
        internal const string SPR_CATEGORY_UPDATECATEGORY = "spr_Category_UpdateCategory";
        internal const string SPR_CATEGORY_DELETECATEGORY = "spr_Category_DeleteCategory";
        internal const string SPR_CATEGORY_DELETECATEGORYLIST = "spr_Category_DeleteCategoryList";
        internal const string SPR_CATEGORY_GETCATEGORYBYID = "spr_Category_GetCategoryById";
        internal const string SPR_CATEGORY_GETALLCATEGORY = "spr_Category_GetAllCategory";
        internal const string SPR_CATEGORY_GETALLCATEGORYPAGED = "spr_Category_GetAllCategoryPaged";
        internal const string SPR_CATEGORY_GETALLCATEGORYPAGEDCOUNT = "spr_Category_GetAllCategoryPagedCount";

		//Foreign key contants
		internal const string SPR_CATEGORY_GETCATEGORYBYPARENTCATEGORYID="spr_Category_GetCategoryByParentCategoryId";
		internal const string SPR_CATEGORY_GETCATEGORYBYPARENTCATEGORYIDPAGED="spr_Category_GetCategoryByParentCategoryIdPaged";
		internal const string SPR_CATEGORY_GETCATEGORYBYPARENTCATEGORYIDPAGEDCOUNT="spr_Category_GetCategoryByParentCategoryIdPagedCount";
		
        #endregion
    }
}
